<template>
  <el-dialog :title="isEdit ? '编辑菜单' : '新增菜单'" v-model="visible" width="600px" @close="handleClose">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="上级菜单" prop="parentId" v-if="!form.parentId">
        <el-tree-select
          v-model="form.parentId"
          :data="parentMenuOptions"
          placeholder="请选择上级菜单"
          clearable
          :props="{
            value: 'id',
            label: 'name',
            children: 'children'
          }"
          class="w-48"
        />
      </el-form-item>
      <el-form-item label="菜单类型" prop="type">
        <el-radio-group v-model="form.type" @change="handleTypeChange">
          <el-radio :label="1">目录</el-radio>
          <el-radio :label="2">菜单</el-radio>
          <el-radio :label="3">按钮</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="菜单名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入菜单名称" />
      </el-form-item>
      <el-form-item label="图标" prop="icon" v-if="form.type !== 3">
        <el-input v-model="form.icon" placeholder="请输入图标名称">
          <template #append>
            <el-icon v-if="form.icon">
              <component :is="form.icon" />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="路由路径" prop="path" v-if="form.type !== 3">
        <el-input v-model="form.path" placeholder="请输入路由路径" />
      </el-form-item>
      <el-form-item label="组件路径" prop="component" v-if="form.type === 2">
        <el-input v-model="form.component" placeholder="请输入组件路径" />
      </el-form-item>
      <el-form-item label="权限标识" prop="permission" v-if="form.type === 3">
        <el-input v-model="form.permission" placeholder="请输入权限标识" />
      </el-form-item>
      <el-form-item label="显示排序" prop="sort">
        <el-input-number
          v-model="form.sort"
          :min="0"
          :max="999"
          controls-position="right"
          class="w-full"
        />
      </el-form-item>
      <el-form-item label="显示状态" prop="visible" v-if="form.type !== 3">
        <el-radio-group v-model="form.visible">
          <el-radio :label="true">显示</el-radio>
          <el-radio :label="false">隐藏</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="菜单状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :label="true">启用</el-radio>
          <el-radio :label="false">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from "vue";
import { ElMessage } from "element-plus";
import { createMenu, updateMenu } from "@/api/menu";

const props = defineProps({
  modelValue: Boolean,
  menuData: Object,
  parentMenus: Array,
});

const emit = defineEmits(["update:modelValue", "success"]);

const formRef = ref();
const loading = ref(false);

const form = reactive({
  id: null,
  parentId: null,
  name: "",
  path: "",
  component: "",
  icon: "",
  type: 1,
  permission: "",
  sort: 0,
  visible: true,
  status: true,
});

const rules = {
  name: [
    { required: true, message: "请输入菜单名称", trigger: "blur" },
    { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" },
  ],
  type: [{ required: true, message: "请选择菜单类型", trigger: "change" }],
  path: [{ required: true, message: "请输入路由路径", trigger: "blur" }],
  component: [{ required: true, message: "请输入组件路径", trigger: "blur" }],
  permission: [{ required: true, message: "请输入权限标识", trigger: "blur" }],
};

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit("update:modelValue", val),
});

const isEdit = computed(() => !!props.menuData);

// 父级菜单选项（树形结构）
const parentMenuOptions = computed(() => {
  const buildTree = (menus, parentId = 0) => {
    return menus
      .filter((menu) => menu.type !== 3) // 按钮不能作为父级菜单
      .filter((menu) => menu.id !== form.id) // 不能选择自己作为父级
      .filter((menu) => menu.parentId === parentId)
      .map((menu) => ({
        id: menu.id,
        name: menu.name,
        type: menu.type,
        children: buildTree(menus, menu.id),
      }));
  };

  // 添加根节点选项
  return [
    {
      id: 0,
      name: "根目录",
      type: 1,
      children: buildTree(props.parentMenus || [], 0),
    },
  ];
});

const resetForm = () => {
  Object.assign(form, {
    id: null,
    parentId: 0,
    name: "",
    path: "",
    component: "",
    icon: "",
    type: 1,
    permission: "",
    sort: 0,
    visible: true,
    status: true,
  });
  formRef.value?.clearValidate();
};

const handleClose = () => {
  visible.value = false;
  resetForm();
};

const handleTypeChange = (type) => {
  // 根据菜单类型清空相关字段
  if (type === 1) {
    // 目录类型
    form.component = "";
    form.permission = "";
  } else if (type === 2) {
    // 菜单类型
    form.permission = "";
  } else if (type === 3) {
    // 按钮类型
    form.path = "";
    form.component = "";
    form.icon = "";
    form.visible = true;
  }
};

const handleSubmit = async () => {
  if (!formRef.value) return;

  // 根据菜单类型动态调整验证规则
  const dynamicRules = { ...rules };

  if (form.type === 1) {
    // 目录类型：不需要组件路径和权限标识
    delete dynamicRules.component;
    delete dynamicRules.permission;
  } else if (form.type === 2) {
    // 菜单类型：不需要权限标识
    delete dynamicRules.permission;
  } else if (form.type === 3) {
    // 按钮类型：只需要权限标识
    delete dynamicRules.path;
    delete dynamicRules.component;
  }

  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true;
      try {
        const submitData = { ...form };

        // 如果parentId为0或空，设置为null
        /* if (!submitData.parentId || submitData.parentId === 0) {
          submitData.parentId = null;
        } */

        if (isEdit.value) {
          await updateMenu(form.id, submitData);
          ElMessage.success("更新成功");
        } else {
          await createMenu(submitData);
          ElMessage.success("创建成功");
        }
        emit("success");
        handleClose();
      } catch (error) {
        ElMessage.error(error.message || "操作失败");
      } finally {
        loading.value = false;
      }
    } else {
      // 表单验证失败处理
    }
  });
};

watch(
  () => props.menuData,
  (newVal) => {
    if (newVal) {
      Object.assign(form, newVal);
    } else {
      resetForm();
    }
  },
  { immediate: true }
);
</script>